package com.vnp.cooking;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.vnp.cooking.bean.ObjAttribute;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.PreferenceHelper;
import com.vnp.cooking.utils.Utils;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class DacDiemMonAnActivity extends Activity implements OnClickListener {

	ImageButton btnBack;
	TextView titleScreen;
	TextView txtThoigiannau, txtLoaibuaan, txtLoaimonan, txtNguongoc,
			txtPhuongphap, txtDokho;
	Button btnDone;

	ArrayList<ObjAttribute> listLoaimonan = new ArrayList<ObjAttribute>();
	ArrayList<ObjAttribute> listLoaibuaan = new ArrayList<ObjAttribute>();
	ArrayList<ObjAttribute> listThoigian = new ArrayList<ObjAttribute>();
	ArrayList<ObjAttribute> listNguongoc = new ArrayList<ObjAttribute>();
	ArrayList<ObjAttribute> listPhuongphap = new ArrayList<ObjAttribute>();
	ArrayList<ObjAttribute> listDokho = new ArrayList<ObjAttribute>();

	PreferenceHelper preferenceHelper;
	
	RelativeLayout llCtTheonguyenlieu, llCtTheoloaimon, llCtTheoloaibuaan,
		frgReplace, llCtTheothoigian, llCtTheonguongoc, llCtTheophuongphap, llCtTheodokho ;

	static int thoigian, loaibuaan, loaimonan, nguongoc, phuongphap, dokho;

	Dialog d, dArlert, dChuapost;
	
	boolean isProccess = false;
	Handler mHandler = new Handler();
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			postDacdiemCT();
		}
	};
	
	Runnable rThoat = new Runnable() {
		
		@Override
		public void run() {
			closeActivity();
		}
	};
	
	ProgressDialog progressDialog;
	private static final String SCREEN_LABEL = "Dac diem mon an screen";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dac_diem_mon_an);

		preferenceHelper = new PreferenceHelper(this);

		btnBack = (ImageButton) findViewById(R.id.btn_back);
		titleScreen = (TextView) findViewById(R.id.title_congthuc_dacdiem);
		/*txtThoigiannau = (TextView) findViewById(R.id.dd_thoigiannau);
		txtLoaibuaan = (TextView) findViewById(R.id.dd_loaibuaan);
		txtLoaimonan = (TextView) findViewById(R.id.dd_loaimonan);
		txtNguongoc = (TextView) findViewById(R.id.dd_nguongoc);
		txtPhuongphap = (TextView) findViewById(R.id.dd_phuongphap);
		txtDokho = (TextView) findViewById(R.id.dd_dokho);*/
		
		llCtTheoloaimon = (RelativeLayout) findViewById(R.id.ll_theoloaimon);
		llCtTheoloaibuaan = (RelativeLayout) findViewById(R.id.ll_theoloaibuaan);
		llCtTheothoigian = (RelativeLayout) findViewById(R.id.ll_theothoigian);
		llCtTheonguongoc = (RelativeLayout) findViewById(R.id.ll_theonguongoc);
		llCtTheophuongphap = (RelativeLayout) findViewById(R.id.ll_theophuongphap);
		llCtTheodokho = (RelativeLayout) findViewById(R.id.ll_theodokho);
		
		
		btnDone = (Button) findViewById(R.id.btn_done_dacdiem);

		if (preferenceHelper.getDataFilter().equals("")) {
			getAttribute();
		}
		loadCache();
		
		setFont();
		init();
		ApplicationContext.getGaTracker().set(Fields.SCREEN_NAME, SCREEN_LABEL);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		ApplicationContext.getGaTracker().send(MapBuilder.createAppView().build());
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	
	private void setFont() {
		titleScreen.setTypeface(Utils.getTypefaceRegular(DacDiemMonAnActivity.this));
		btnDone.setTypeface(Utils.getTypefaceRegular(DacDiemMonAnActivity.this));
	}

	void init() {
		llCtTheoloaimon.setOnClickListener(this);
		llCtTheoloaibuaan.setOnClickListener(this);
		llCtTheothoigian.setOnClickListener(this);
		llCtTheonguongoc.setOnClickListener(this);
		llCtTheophuongphap.setOnClickListener(this);
		llCtTheodokho.setOnClickListener(this);
		btnBack.setOnClickListener(this);
		btnDone.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			/*if (isProccess == true) {
				showDialogProcess();
			} else {
				if ((preferenceHelper.getIdThoigian() == 0)||(preferenceHelper.getIdLoaimon() == 0)||(preferenceHelper.getIdLoaibua() == 0)
					||(preferenceHelper.getIdPhuongphap()==0)||(preferenceHelper.getIdDokho() == 0)||(preferenceHelper.getIdNguongoc() == 0) ) {
					showDialogCanhbaochuapost();
				} else {
					closeActivity();
					preferenceHelper.setIdThoigian(-1);
					preferenceHelper.setIdLoaimonan(-1);
					preferenceHelper.setIdLoaibua(-1);
					preferenceHelper.setIdPhuongphap(-1);
					preferenceHelper.setIdDokho(-1);
					preferenceHelper.setIdNguongoc(-1);
//				}
			}*/
			
			if ((preferenceHelper.getIdThoigian() != -1)||(preferenceHelper.getIdLoaimon() != -1)||(preferenceHelper.getIdLoaibua() != -1)
					||(preferenceHelper.getIdPhuongphap() != -1)||(preferenceHelper.getIdDokho() != -1)||(preferenceHelper.getIdNguongoc() != -1) ) {
				
				isProccess = true;
				progressDialog = ProgressDialog.show(this, "", "Đang cập nhật đặc điểm công thức...");
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						if (null != progressDialog && progressDialog.isShowing())
							progressDialog.dismiss();
					}
				}, 90000);
				mHandler.removeCallbacks(r);
				mHandler.post(r);
				
				
			} else {
				closeActivity();
				DangCongThucActivity.isPostedDacdiem = false;
				preferenceHelper.setIdThoigian(-1);
				preferenceHelper.setIdLoaimonan(-1);
				preferenceHelper.setIdLoaibua(-1);
				preferenceHelper.setIdPhuongphap(-1);
				preferenceHelper.setIdDokho(-1);
				preferenceHelper.setIdNguongoc(-1);
			}
			
			
			break;
		case R.id.ll_theothoigian:
			Intent t1 = new Intent(DacDiemMonAnActivity.this,
					DetailDacdiemActivity.class);
			t1.putParcelableArrayListExtra("listDetail", getDetailValue(1));
			for (int i = 0; i < getDetailValue(1).size(); i++) {
				Log.i("Test", "ID: " + getDetailValue(1).get(i).getId());
			}
			t1.putExtra("title", getTitle(1));
			t1.putExtra("type", 1);
			startActivity(t1);
			overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
		case R.id.ll_theoloaibuaan:
			Intent t2 = new Intent(DacDiemMonAnActivity.this,
					DetailDacdiemActivity.class);
			t2.putParcelableArrayListExtra("listDetail", getDetailValue(2));
			t2.putExtra("title", getTitle(2));
			t2.putExtra("type", 2);
			startActivity(t2);
			overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
		case R.id.ll_theoloaimon:
			Intent t3 = new Intent(DacDiemMonAnActivity.this,
					DetailDacdiemActivity.class);
			t3.putParcelableArrayListExtra("listDetail", getDetailValue(3));
			t3.putExtra("title", getTitle(3));
			t3.putExtra("type", 3);
			startActivity(t3);
			overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
		case R.id.ll_theonguongoc:
			Intent t4 = new Intent(DacDiemMonAnActivity.this,
					DetailDacdiemActivity.class);
			t4.putParcelableArrayListExtra("listDetail", getDetailValue(4));
			t4.putExtra("title", getTitle(4));
			t4.putExtra("type", 4);
			startActivity(t4);
			overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
		case R.id.ll_theophuongphap:
			Intent t5 = new Intent(DacDiemMonAnActivity.this,
					DetailDacdiemActivity.class);
			t5.putParcelableArrayListExtra("listDetail", getDetailValue(5));
			t5.putExtra("title", getTitle(5));
			t5.putExtra("type", 5);
			startActivity(t5);
			overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
		case R.id.ll_theodokho:
			Intent t6 = new Intent(DacDiemMonAnActivity.this,
					DetailDacdiemActivity.class);
			t6.putParcelableArrayListExtra("listDetail", getDetailValue(6));
			t6.putExtra("title", getTitle(6));
			t6.putExtra("type", 6);
			startActivity(t6);
			overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
		case R.id.btn_done_dacdiem:
			isProccess = true;
			progressDialog = ProgressDialog.show(this, "", "Đang cập nhật đặc điểm công thức...");
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					if (null != progressDialog && progressDialog.isShowing())
						progressDialog.dismiss();
				}
			}, 90000);
			mHandler.removeCallbacks(r);
			mHandler.post(r);
			break;
		default:
			break;
		}
	}

	public ArrayList<ObjAttribute> getDetailValue(int type) {

		if (type == 1) {
			return listThoigian;
		}
		if (type == 2) {
			return listLoaibuaan;
		}
		if (type == 3) {
			return listLoaimonan;
		}
		if (type == 4) {
			return listNguongoc;
		}
		if (type == 5) {
			return listPhuongphap;
		}
		if (type == 6) {
			return listDokho;
		}

		return null;
	}

	String getTitle(int type) {
		String title = null;
		switch (type) {
		case 1:
			title = "Thời gian nấu";
			break;

		case 2:
			title = "Loại bữa ăn";
			break;
		case 3:
			title = "Loại món ăn";
			break;
		case 4:
			title = "Nguồn gốc";
			break;
		case 5:
			title = "Phương pháp nấu";
			break;
		case 6:
			title = "Độ khó";
			break;
		}
		return title;
	}

	void getAttribute() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
					}

					@Override
					public void onSuccess(JSONObject re) {
						try {
							if (!re.toString().equals("")) {
								preferenceHelper.setDataFilter(re.toString());
							}
						} catch (Exception e) {
						}
						parseData(re);
					}

				});
		httpClientHelper.getThuoctinh();
	}

	void loadCache() {
		String cache = preferenceHelper.getDataFilter();
		if (!cache.equals("")) {
			try {
				JSONObject response = new JSONObject(cache);
				parseData(response);
			} catch (Exception e) {
			}
		}
	}

	public void parseData(JSONObject re) {
		try {
			int status = re.getInt("status");
			if (status == 200) {
				listDokho.clear();
				listLoaibuaan.clear();
				listLoaimonan.clear();
				listNguongoc.clear();
				listPhuongphap.clear();
				listThoigian.clear();
				JSONObject data = re.getJSONObject("data");
				JSONArray params = data.getJSONArray("param");
				Log.i("DATA", "ATRIBUTE: " + params);
				// get loai mon an
				JSONObject loaimon = params.getJSONObject(0);
				JSONArray loaimonParams = loaimon.getJSONArray("params");
				for (int i = 0; i < loaimonParams.length(); i++) {
					ObjAttribute objAttribute = new ObjAttribute();
					JSONObject loaimonParam = loaimonParams.getJSONObject(i);
					String alias = loaimonParam.getString("alias");
					int id = loaimonParam.getInt("id");
					String name = loaimonParam.getString("name");
					objAttribute.setAlias(alias);
					objAttribute.setId(id);
					objAttribute.setName(name);
					listLoaimonan.add(objAttribute);
				}

				// get loai bua an
				JSONObject loaibuaan = params.getJSONObject(1);
				JSONArray loaibuaanParams = loaibuaan.getJSONArray("params");
				for (int i = 0; i < loaibuaanParams.length(); i++) {
					ObjAttribute objAttribute = new ObjAttribute();
					JSONObject loaibuaanParam = loaibuaanParams
							.getJSONObject(i);
					String alias = loaibuaanParam.getString("alias");
					int id = loaibuaanParam.getInt("id");
					String name = loaibuaanParam.getString("name");
					objAttribute.setAlias(alias);
					objAttribute.setId(id);
					objAttribute.setName(name);
					listLoaibuaan.add(objAttribute);
				}

				// get thoi gian
				JSONObject thoigian = params.getJSONObject(2);
				JSONArray thoigianParams = thoigian.getJSONArray("params");
				for (int i = 0; i < thoigianParams.length(); i++) {
					ObjAttribute objAttribute = new ObjAttribute();
					JSONObject thoigianParam = thoigianParams.getJSONObject(i);
					String alias = thoigianParam.getString("alias");
					int id = thoigianParam.getInt("id");
					String name = thoigianParam.getString("name");
					objAttribute.setAlias(alias);
					objAttribute.setId(id);
					objAttribute.setName(name);
					listThoigian.add(objAttribute);
				}

				// get nguon goc
				JSONObject nguongoc = params.getJSONObject(3);
				JSONArray nguongocParams = nguongoc.getJSONArray("params");
				for (int i = 0; i < nguongocParams.length(); i++) {
					ObjAttribute objAttribute = new ObjAttribute();
					JSONObject nguongocParam = nguongocParams.getJSONObject(i);
					String alias = nguongocParam.getString("alias");
					int id = nguongocParam.getInt("id");
					String name = nguongocParam.getString("name");
					objAttribute.setAlias(alias);
					objAttribute.setId(id);
					objAttribute.setName(name);
					listNguongoc.add(objAttribute);
				}

				// get phuong phap
				JSONObject phuongphap = params.getJSONObject(4);
				JSONArray phuongphapParams = phuongphap.getJSONArray("params");
				for (int i = 0; i < phuongphapParams.length(); i++) {
					ObjAttribute objAttribute = new ObjAttribute();
					JSONObject phuongphapParam = phuongphapParams
							.getJSONObject(i);
					String alias = phuongphapParam.getString("alias");
					int id = phuongphapParam.getInt("id");
					String name = phuongphapParam.getString("name");
					objAttribute.setAlias(alias);
					objAttribute.setId(id);
					objAttribute.setName(name);
					listPhuongphap.add(objAttribute);
				}

				// get do kho
				JSONObject dokho = params.getJSONObject(5);
				JSONArray dokhoParams = dokho.getJSONArray("params");
				for (int i = 0; i < dokhoParams.length(); i++) {
					ObjAttribute objAttribute = new ObjAttribute();
					JSONObject dokhoParam = dokhoParams.getJSONObject(i);
					String alias = dokhoParam.getString("alias");
					int id = dokhoParam.getInt("id");
					String name = dokhoParam.getString("name");
					objAttribute.setAlias(alias);
					objAttribute.setId(id);
					objAttribute.setName(name);
					listDokho.add(objAttribute);
				}

			} else {
				Toast.makeText(DacDiemMonAnActivity.this,
						"Không lấy được dữ liệu", Toast.LENGTH_SHORT)
						.show();
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Toast.makeText(DacDiemMonAnActivity.this,
					"Không lấy được dữ liệu", Toast.LENGTH_SHORT)
					.show();
		}
	}

	// put dac diem mon an
	void postDacdiemCT() {
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
						isProccess = false;
						progressDialog.dismiss();
						Toast.makeText(DacDiemMonAnActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onSuccess(JSONObject re) {
						isProccess = false;
						progressDialog.dismiss();
						try {
							int status = re.getInt("status");
							switch (status) {
							case 200:
								DangCongThucActivity.isPostedDacdiem = true;
								Toast.makeText(DacDiemMonAnActivity.this, "Cập nhật thành công.", Toast.LENGTH_SHORT).show();
								Log.i("DATA", "CAP nhat dac diem thanh cong");
								mHandler.postDelayed(rThoat, 200);
								break;
							case 400:
								Toast.makeText(DacDiemMonAnActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
								Log.i("DATA",
										"CAP nhat dac diem : thieu truong");
								break;
							case 404:
								Toast.makeText(DacDiemMonAnActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
								Log.i("DATA",
										"CAP nhat dac diem : id khac recipe");
								break;

							default:
								break;
							}
						} catch (JSONException e) {
							e.printStackTrace();
							isProccess = false;
							progressDialog.dismiss();
						}
					}

				});
		JSONArray data = new JSONArray();
		if (preferenceHelper.getIdThoigian() == -1) {
			
		} else {
			data.put(preferenceHelper.getIdThoigian());
		}
		
		if (preferenceHelper.getIdLoaibua() == -1) {
			
		} else {
			data.put(preferenceHelper.getIdLoaibua());
		}
		
		if (preferenceHelper.getIdLoaimon() == -1) {
					
		} else {
			data.put(preferenceHelper.getIdLoaimon());		
		}

		if (preferenceHelper.getIdNguongoc() == -1) {
			
		} else {
			data.put(preferenceHelper.getIdNguongoc());
		}

		if (preferenceHelper.getIdPhuongphap() == -1) {
			
		} else {
			data.put(preferenceHelper.getIdPhuongphap());
		}

		if (preferenceHelper.getIdDokho() == -1) {
			
		} else {
			data.put(preferenceHelper.getIdDokho());
		}
		
		httpClientHelper.updateDacdiem(preferenceHelper.getID(),
				preferenceHelper.getRecipeId(), data);

	}

	void closeActivity() {
		finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
	}

	@Override
	public void onBackPressed() {
		closeActivity();
	}

	void showDialogCapnhatNguyenlieuthanhcong() {
		d = new Dialog(this, R.style.DialogSlideAnimLeft);
		d.requestWindowFeature(Window.FEATURE_NO_TITLE);
		d.setContentView(R.layout.dialog_chua_hotro);
		TextView txtThongbao = (TextView) d
				.findViewById(R.id.str_canhbao_thoat);

		Button btnDong = (Button) d.findViewById(R.id.btn_dong);

		txtThongbao.setText("Bạn đã cập nhật đặc điểm thành công.");
		d.show();
		d.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		d.setCanceledOnTouchOutside(true);
		d.getWindow().setGravity(Gravity.CENTER);
		d.show();

		// setonclick
		btnDong.setOnClickListener(this);
	}

	// show dialog dang thuc hien 1 hanh dong noa do
	public void showDialogProcess() {
		dArlert = new Dialog(DacDiemMonAnActivity.this,
				R.style.DialogSlideAnimLeft);
		dArlert.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dArlert.setContentView(R.layout.dialog_thoat_process);

		// khai bao cac thanh phan
		TextView txtArlert = (TextView) dArlert
				.findViewById(R.id.str_canhbao_thoat);
		Button btnThoat = (Button) dArlert.findViewById(R.id.btn_thoat);
		Button btnKoThoat = (Button) dArlert.findViewById(R.id.btn_ko_thoat);

		btnThoat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dArlert.dismiss();
				mHandler.removeCallbacks(r);
				preferenceHelper.setIdThoigian(-1);
				preferenceHelper.setIdLoaimonan(-1);
				preferenceHelper.setIdLoaibua(-1);
				preferenceHelper.setIdPhuongphap(-1);
				preferenceHelper.setIdDokho(-1);
				preferenceHelper.setIdNguongoc(-1);
				closeActivity();
			}
		});

		btnKoThoat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dArlert.dismiss();
			}
		});

		dArlert.setCanceledOnTouchOutside(true);
		dArlert.show();
		dArlert.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dArlert.getWindow().setGravity(Gravity.CENTER);
	}

	void showDialogCanhbaochuapost() {
		dChuapost = new Dialog(DacDiemMonAnActivity.this,
				R.style.DialogSlideAnimLeft);
		dChuapost.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dChuapost.setContentView(R.layout.dialog_thoat_process);

		// khai bao cac thanh phan
		TextView txtArlert = (TextView) dChuapost
				.findViewById(R.id.str_canhbao_thoat);
		Button btnThoat = (Button) dChuapost.findViewById(R.id.btn_thoat);
		Button btnKoThoat = (Button) dChuapost.findViewById(R.id.btn_ko_thoat);

		txtArlert
				.setText("Bạn chưa cập nhật đặc điểm. Bạn có muốn bỏ qua cập nhật và thoát?");
		btnThoat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dChuapost.dismiss();
				preferenceHelper.setIdThoigian(0);
				preferenceHelper.setIdLoaimonan(0);
				preferenceHelper.setIdLoaibua(0);
				preferenceHelper.setIdPhuongphap(0);
				preferenceHelper.setIdDokho(0);
				preferenceHelper.setIdNguongoc(0);
				closeActivity();
			}
		});

		btnKoThoat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dChuapost.dismiss();
			}
		});

		dChuapost.setCanceledOnTouchOutside(true);
		dChuapost.show();
		dChuapost.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dChuapost.getWindow().setGravity(Gravity.CENTER);
	}

}
